//
//  AppDelegate.m
//  Zhihuijinfu
//
//  Created by 王笛 on 2016/11/28.
//  Copyright © 2016年 王笛. All rights reserved.
//

#import "AppDelegate.h"
#import "WDNavController.h"
#import "WDLoginController.h"
#import "ControllerTool.h"
#import "IQKeyboardManager.h"
#import "LeftMenViewController.h"
#import "WDHTTPMethod.h"
#import "WDCarList.h"
#import "WDStseries.h"
#import "WDUploadData.h"
#import "WDTempController.h"
#import <AMapFoundationKit/AMapFoundationKit.h>
typedef void (^uploadFinish)();

typedef void (^uploadError)();

static NSString *const WDUploadStatusNotificaton = @"WDUploadStatusNotificaton";

// iOS10        UserNotifications.framework
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 
#import <UserNotifications/UserNotifications.h>
#endif

@interface AppDelegate () <UNUserNotificationCenterDelegate>

/** 车型数组 */
@property (nonatomic, strong) NSArray *carList;

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
    //高德
    [self xyVerifyAMapKey];
    /*************************** 个推推送 ***************************/
    //启动个推
    [GeTuiSdk startSdkWithAppId:kGtAppId appKey:kGtAppKey appSecret:kGtAppSecret delegate:self];
    
    //    注册APNs
    [self registerRemoteNotification];
    
    /******************* IQKeyBoardManager设置 *********************/
    IQKeyboardManager *manager = [IQKeyboardManager sharedManager];
    
    manager.enable = YES;
    
    manager.shouldResignOnTouchOutside = YES;
    
    manager.enableAutoToolbar = YES;
    
    manager.toolbarManageBehaviour =IQAutoToolbarByTag;
    
    //********************** 请求公用数据 ******************************
    
    //打开上传图片的任务
    WDSQLiteManager *sqlManager = [WDSQLiteManager manager];
    [sqlManager creatTable:NSStringFromClass([WDUploadData class]) WithPrimaryKey:nil];
    //修改“上传失败”、“正在上传”为“未上传”状态
    NSArray *uploadData = [sqlManager selectWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"status":@(UploadStatusError)}];
    if (uploadData) {
        [sqlManager updateWithTable:NSStringFromClass([WDUploadData class]) setKeyValues:@{@"status":@(UploadStatusWaiting)} whereCondition:@{@"status":@(UploadStatusError)}];
    }
    
    uploadData = [sqlManager selectWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"status":@(UploadStatusRunning)}];
    if (uploadData) {
        [sqlManager updateWithTable:NSStringFromClass([WDUploadData class]) setKeyValues:@{@"status":@(UploadStatusWaiting)} whereCondition:@{@"status":@(UploadStatusRunning)}];
    }
    
    uploadData = [sqlManager selectWithTable:NSStringFromClass([WDUploadData class]) whereCondition:@{@"status":@(UploadStatusWaiting)}];
    //执行上传操作
    if (uploadData.count) {
        [self uploadImage];
    }
    
    
    NSString *time_stamp = [[NSUserDefaults standardUserDefaults] objectForKey:WDTimeStampLaunch];
    
    time_stamp = (time_stamp == nil ? @"" : time_stamp);
    
    NSDictionary *bodyDic = @{
                              @"time_stamp":time_stamp,
                              @"ctype":@3
                              };
    
    //车型
    [WDHTTPMethod getDataByString:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLListBrand] BODYDic:bodyDic WithDataBlock:^(id data) {
        
        NSMutableArray *carLists = [WDCarList mj_objectArrayWithKeyValuesArray:data[@"data"]];
        
        //归档
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        NSString *archiverPath = [path stringByAppendingPathComponent:WDCarListFile];
        
        if ([NSKeyedArchiver archiveRootObject:carLists toFile:archiverPath]) {
//            WDLog(@"车品牌信息归档成功");
        }
        
    }];
    
    //车系
    [WDHTTPMethod getDataByString:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLListSeries] BODYDic:bodyDic WithDataBlock:^(id data) {
        
        NSMutableArray *seriesLists = [WDStseries mj_objectArrayWithKeyValuesArray:data[@"data"]];
        
        //归档
        NSString *path = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
        
        NSString *archiverPath = [path stringByAppendingPathComponent:WDCarSeriesFile];
        
//        WDLog(@"%@", archiverPath);
        
        if ([NSKeyedArchiver archiveRootObject:seriesLists toFile:archiverPath]) {
//            WDLog(@"车系信息归档成功");
        }
        
    }];
    
    //+++++++++++++++++++++++ 控制器设置 ++++++++++++++++++++++++++++++
    self.window = [[UIWindow alloc] initWithFrame:[UIScreen mainScreen].bounds];
    
    NSUserDefaults *userDefault = [NSUserDefaults standardUserDefaults];
    
    WDTempController *tempVC = [[WDTempController alloc] init];
    
    tempVC.view.backgroundColor = [UIColor whiteColor];
    
    self.window.rootViewController = [[UINavigationController alloc] initWithRootViewController:tempVC];
    
    [_window makeKeyAndVisible];
    
    if (![userDefault boolForKey:@"loginAgain"]) {

        WDLoginController *tempVC = [[WDLoginController alloc] init];
        
        tempVC.view.backgroundColor = [UIColor whiteColor];
        
        self.window.rootViewController = [[WDNavController alloc] initWithRootViewController:tempVC];
        
        [_window makeKeyAndVisible];
    } else {
        
        [self checkNewWorking];
    }
    
    return YES;
}

- (void)xyVerifyAMapKey{
    if ([xyGaodeKey length] == 0)
    {
        NSString *reason = [NSString stringWithFormat:@"apiKey为空，请检查key是否正确设置。"];
        
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:reason delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        
        [alert show];
    }
    
    [AMapServices sharedServices].apiKey = (NSString *)xyGaodeKey;

}

- (void)checkNewWorking
{
    AFNetworkReachabilityManager *manager = [AFNetworkReachabilityManager sharedManager];
    
    [manager setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
        
        switch (status) {
            case AFNetworkReachabilityStatusUnknown:
            {
                
                [WDPromptBox showPromptBoxWithMassage:@"未识别的网络"];
                
                UIViewController *tempVC = [[ControllerTool shareOpenController] getDrawerController];
                self.window.rootViewController = tempVC;
                
                [_window makeKeyAndVisible];
                
            }
                break;
                
            case AFNetworkReachabilityStatusNotReachable:
            {
                
                [WDPromptBox showPromptBoxWithMassage:@"网络连接中断"];
                
                UIViewController *tempVC = [[ControllerTool shareOpenController] getDrawerController];
                self.window.rootViewController = tempVC;
                
                [_window makeKeyAndVisible];
                
            }
                break;
                
            case AFNetworkReachabilityStatusReachableViaWWAN:
                
                [self verifyLogin];
                
                break;
                
            case AFNetworkReachabilityStatusReachableViaWiFi:
                
                [self verifyLogin];
                
                break;
            default:
                break;
        }
        
    }];
    
    //开始监听
    [manager startMonitoring];
    
}

#pragma mark - 验证登录
- (void)verifyLogin
{
    //验证登录信息
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSDictionary *parameters = @{
                                 @"ctype":@3
                                 };
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    
    NSString *loginCookie;
    
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            
//            WDLog(@"%@", cookie);
            
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
            if ([cookie.name isEqualToString:@"logininfo"]) {
                loginCookie = [MD5Util md5:[NSString stringWithFormat:@"%@%@", cookie.value, @"zhihjf"]];
            }
        }
    }
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLoginAgain];
    
    [manager POST:url parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        if ([loginCookie isEqualToString:responseObject[@"verify_string"]] && [[[NSUserDefaults standardUserDefaults] objectForKey:@"userName"] isEqualToString:responseObject[@"account"]] && ([[[NSUserDefaults standardUserDefaults] objectForKey:@"workCity"] intValue] ==[responseObject[@"work_city"] intValue])) {
            
            UIViewController *tempVC = [[ControllerTool shareOpenController] getDrawerController];
            self.window.rootViewController = tempVC;
            
            [_window makeKeyAndVisible];
            
        } else {
            
            //清除数据
            NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
            
            [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
            
            WDSQLiteManager *manager = [WDSQLiteManager manager];
            [manager clearTable:@"WDBusiness"];
            [manager clearTable:@"WDProduct"];
            
            //清除BadgeNumber
            [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
            
            [GeTuiSdk setBadge:0];
            
            WDLoginController *tempVC = [[WDLoginController alloc] init];
            
            tempVC.view.backgroundColor = [UIColor whiteColor];
            
            self.window.rootViewController = [[WDNavController alloc] initWithRootViewController:tempVC];
            
            [_window makeKeyAndVisible];
        }
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
        //清除数据
        NSString *appDomain = [[NSBundle mainBundle] bundleIdentifier];
        
        [[NSUserDefaults standardUserDefaults] removePersistentDomainForName:appDomain];
        
        WDSQLiteManager *manager = [WDSQLiteManager manager];
        [manager clearTable:@"WDBusiness"];
        [manager clearTable:@"WDProduct"];
        
        //清除BadgeNumber
        [UIApplication sharedApplication].applicationIconBadgeNumber = 0;
        
        [GeTuiSdk setBadge:0];
        
        WDLoginController *tempVC = [[WDLoginController alloc] init];
        
        tempVC.view.backgroundColor = [UIColor whiteColor];
        
        self.window.rootViewController = [[WDNavController alloc] initWithRootViewController:tempVC];
        
        [_window makeKeyAndVisible];
        
//        WDLog(@"%@",error);
        
    }];
}

#pragma mark - 上传图片方法
- (void)uploadImage
{
    //上传状态为YES
    [[NSUserDefaults standardUserDefaults] setBool:YES forKey:@"uploadRunning"];
    
    WDSQLiteManager *manager = [WDSQLiteManager manager];
    
    NSArray *uploadImages = [manager selectWithTable:NSStringFromClass([WDUploadData class])whereCondition:@{@"status":@(UploadStatusWaiting)}];
    
    //判断数据库是否等于0
    if (uploadImages.count == 0) {
        [[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"uploadRunning"];
        return ;
    }
    
    WDUploadData *uploadData = uploadImages[0];
    
    UIImage *uploadImage = [UIImage imageWithContentsOfFile:[WDCachePath stringByAppendingPathComponent:uploadData.imagePath]];
    NSData *imageData = UIImageJPEGRepresentation(uploadImage, 1.0);
    
    //上传操作
    [self uploadRequest:imageData financeId:uploadData.financeId fileType:[NSString stringWithFormat:@"%zd", uploadData.imageType] fileName:uploadData.imageName uploadFinish:^{
        //成功状态
        NSDictionary *keyValues = @{
                                    @"status":@(UploadStatusFinish)
                                    };
        
        NSDictionary *condition = @{
                                    @"imagePath":uploadData.imagePath
                                    };
        
        [manager updateWithTable:NSStringFromClass([WDUploadData class]) setKeyValues:keyValues whereCondition:condition];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:WDUploadStatusNotificaton object:nil];
        
        [self uploadImage];
        
    } uploadError:^{
        //失败状态
        [manager updateWithTable:NSStringFromClass([WDUploadData class]) setKeyValues:@{@"status":@(UploadStatusError)} whereCondition:@{@"imageName":uploadData.imagePath}];
        
        [[NSNotificationCenter defaultCenter] postNotificationName:WDUploadStatusNotificaton object:nil];
        
        
        [self uploadImage];
    }];
    
    
}

- (void)uploadRequest:(NSData *)imageData financeId:(NSString *)financeId fileType:(NSString *)fileType fileName:(NSString *)fileName uploadFinish:(uploadFinish)uploadFinish uploadError:(uploadError)uploadError
{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    
    NSData *cookiesdata = [[NSUserDefaults standardUserDefaults] objectForKey:[NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLLogin]];
    if([cookiesdata length]) {
        NSArray *cookies = [NSKeyedUnarchiver unarchiveObjectWithData:cookiesdata];
        NSHTTPCookie *cookie;
        for (cookie in cookies) {
            [[NSHTTPCookieStorage sharedHTTPCookieStorage] setCookie:cookie];
        }
    }
    
    NSDictionary *parameters = @{
                                 @"finance_id":financeId,
                                 @"file_type":fileType,
                                 @"file_name":fileName,
                                 @"material_type":@1,
                                 @"ctype":@3
                                 };
    NSString *url = [NSString stringWithFormat:@"%@%@", WDURLPrefix, WDURLFinanceFileUpLoad];
    
    [manager POST:url parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        //上传图片
        // 可以在上传时使用当前的系统时间作为文件名
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        // 设置时间格式
        formatter.dateFormat = @"yyyyMMddHHmmss";
        NSString *str = [formatter stringFromDate:[NSDate date]];
        NSString *fileName = [NSString stringWithFormat:@"%@.jpg", str];
        
        [formData appendPartWithFileData:imageData name:@"file" fileName:fileName mimeType:@"image/jpeg"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        //上传成功，修改状态
        uploadFinish();
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        //上传失败，修改状态
        uploadError();
    }];
}

#pragma mark - 用户通知(推送) _自定义方法

/** 注册远程通知 */
- (void)registerRemoteNotification {
    /*
     警告：该方法需要开发者自定义，以下代码根据APP支持的iOS系统不同，代码可以对应修改。
     以下为演示代码，注意根据实际需要修改，注意测试支持的iOS系统都能获取到DeviceToken
     */
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 10.0) {
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0 // Xcode 8编译会调用
        UNUserNotificationCenter *center = [UNUserNotificationCenter currentNotificationCenter];
        center.delegate = self;
        [center requestAuthorizationWithOptions:(UNAuthorizationOptionBadge | UNAuthorizationOptionSound | UNAuthorizationOptionAlert | UNAuthorizationOptionCarPlay) completionHandler:^(BOOL granted, NSError *_Nullable error) {
            if (!error) {
//                WDLog(@"request authorization succeeded!");
            }
        }];
        
        [[UIApplication sharedApplication] registerForRemoteNotifications];
        
#else // Xcode 7编译会调用
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
#endif
    } else if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 8.0) {
        UIUserNotificationType types = (UIUserNotificationTypeAlert | UIUserNotificationTypeSound | UIUserNotificationTypeBadge);
        UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:types categories:nil];
        [[UIApplication sharedApplication] registerUserNotificationSettings:settings];
        [[UIApplication sharedApplication] registerForRemoteNotifications];
    } else {
        UIRemoteNotificationType apn_type = (UIRemoteNotificationType)(UIRemoteNotificationTypeAlert |
                                                                       UIRemoteNotificationTypeSound |
                                                                       UIRemoteNotificationTypeBadge);
        [[UIApplication sharedApplication] registerForRemoteNotificationTypes:apn_type];
    }
}

/** 远程通知注册成功委托 */
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    NSString *token = [[deviceToken description] stringByTrimmingCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"<>"]];
    token = [token stringByReplacingOccurrencesOfString:@" " withString:@""];
    WDLog(@"\n>>>[DeviceToken Success]:%@\n\n", token);
    
    // [ GTSdk ]：向个推服务器注册deviceToken
    [GeTuiSdk registerDeviceToken:token];
}

/** 远程通知注册失败委托 */
- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    WDLog(@"\n>>>[DeviceToken Error]:%@\n\n", error.description);
}

- (void)application:(UIApplication *)application performFetchWithCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    
    [GeTuiSdk resume];
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - APP运行中接收到通知(推送)处理 - iOS 10以下版本收到推送

/** APP已经接收到“远程”通知(推送) - 透传推送消息  */
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult result))completionHandler {
    
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:userInfo];
    
    // 控制台打印接收APNs信息
    WDLog(@"\n>>>[Receive RemoteNotification]:%@\n\n", userInfo);
    
    completionHandler(UIBackgroundFetchResultNewData);
}

#pragma mark - iOS 10中收到推送消息

#if __IPHONE_OS_VERSION_MAX_ALLOWED >= __IPHONE_10_0
//  iOS 10: App在前台获取到通知
- (void)userNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(UNNotificationPresentationOptions))completionHandler {
    
    WDLog(@"willPresentNotification：%@", notification.request.content.userInfo);
    
    // 根据APP需要，判断是否要提示用户Badge、Sound、Alert
    completionHandler(UNNotificationPresentationOptionBadge | UNNotificationPresentationOptionSound | UNNotificationPresentationOptionAlert);
}

//  iOS 10: 点击通知进入App时触发
- (void)userNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    
    //跳转到我的通知
    
    ControllerTool *tool = [ControllerTool shareOpenController];
    
    tool.isNotify = YES;
    
    [[UIApplication sharedApplication].delegate window].rootViewController = [tool getDrawerController];
    
    LeftMenViewController *leftVC = (LeftMenViewController *)[[ControllerTool shareOpenController] getDrawerController].leftDrawerViewController;
    leftVC.defaultIndex = 7;
    tool.isNotify = NO;
    
    WDLog(@"didReceiveNotification：%@", response.notification.request.content.userInfo);
    
    // [ GTSdk ]：将收到的APNs信息传给个推统计
    [GeTuiSdk handleRemoteNotification:response.notification.request.content.userInfo];
    
    completionHandler();
}
#endif

#pragma mark - GeTuiSdkDelegate

/** SDK启动成功返回cid */
- (void)GeTuiSdkDidRegisterClient:(NSString *)clientId {
    // [4-EXT-1]: 个推SDK已注册，返回clientId
    WDLog(@"\n>>[GTSdk RegisterClient]:%@\n\n", clientId);
    
    //保存cid
    [[NSUserDefaults standardUserDefaults] setObject:clientId forKey:@"clientId"];
    
}

/** SDK遇到错误回调 */
- (void)GeTuiSdkDidOccurError:(NSError *)error {
    // [EXT]:个推错误报告，集成步骤发生的任何错误都在这里通知，如果集成后，无法正常收到消息，查看这里的通知。
    WDLog(@"\n>>[GTSdk error]:%@\n\n", [error localizedDescription]);
}


/** SDK收到透传消息回调 */
- (void)GeTuiSdkDidReceivePayloadData:(NSData *)payloadData andTaskId:(NSString *)taskId andMsgId:(NSString *)msgId andOffLine:(BOOL)offLine fromGtAppId:(NSString *)appId {
    // [ GTSdk ]：汇报个推自定义事件(反馈透传消息)
    [GeTuiSdk sendFeedbackMessage:90019 andTaskId:taskId andMsgId:msgId];
    
    // 数据转换
    NSString *payloadMsg = nil;
    if (payloadData) {
        payloadMsg = [[NSString alloc] initWithBytes:payloadData.bytes length:payloadData.length encoding:NSUTF8StringEncoding];
    }
    
    if ([[UIDevice currentDevice].systemVersion doubleValue] < 10.0) {
        
        //跳转到我的通知
        ControllerTool *tool = [ControllerTool shareOpenController];
        
        tool.isNotify = YES;
        
        [[UIApplication sharedApplication].delegate window].rootViewController = [tool getDrawerController];
        
        LeftMenViewController *leftVC = (LeftMenViewController *)[[ControllerTool shareOpenController] getDrawerController].leftDrawerViewController;
        leftVC.defaultIndex = 7;
        tool.isNotify = NO;
        
    }
    
    
    
    // 控制台打印日志
    NSString *msg = [NSString stringWithFormat:@"taskId=%@,messageId:%@,payloadMsg:%@%@", taskId, msgId, payloadMsg, offLine ? @"<离线消息>" : @""];
    WDLog(@"\n>>[GTSdk ReceivePayload]:%@\n\n", msg);
}

/** SDK收到sendMessage消息回调 */
- (void)GeTuiSdkDidSendMessage:(NSString *)messageId result:(int)result {
    // 发送上行消息结果反馈
    NSString *msg = [NSString stringWithFormat:@"sendmessage=%@,result=%d", messageId, result];
    WDLog(@"\n>>[GTSdk DidSendMessage]:%@\n\n", msg);
}

/** SDK运行状态通知 */
- (void)GeTuiSDkDidNotifySdkState:(SdkStatus)aStatus {
    // 通知SDK运行状态
    WDLog(@"\n>>[GTSdk SdkState]:%u\n\n", aStatus);
}

/** SDK设置推送模式回调 */
- (void)GeTuiSdkDidSetPushMode:(BOOL)isModeOff error:(NSError *)error {
    if (error) {
        WDLog(@"\n>>[GTSdk SetModeOff Error]:%@\n\n", [error localizedDescription]);
        return;
    }
    
    WDLog(@"\n>>[GTSdk SetModeOff]:%@\n\n", isModeOff ? @"开启" : @"关闭");
}


- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


- (void)applicationDidEnterBackground:(UIApplication *)application {
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}


@end
